package com.test.controller;

import org.jbarcode.JBarcode;
import org.jbarcode.encode.Code39Encoder;
import org.jbarcode.encode.InvalidAtributeException;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.jbarcode.util.ImageUtil;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    @RequestMapping("/hello")
    public String test() {
        return "hello";
    }

    @RequestMapping("/image")
    @ResponseBody
    String image() {
        return Base64Test.GetImageStr();
//        String str = "<html><body><img src='data:image/jpg;base64," +
//                Base64Test.GetImageStr() + "' >" +
//                "</body></html>";
//        return str;
    }

    @RequestMapping(value = "/jbarcode.do")
    @ResponseBody
    public String generateBarCode39(String strBarCode, String dimension, String barHeight, String barWith, HttpServletResponse response, HttpServletRequest request) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            JBarcode productBarcode = new JBarcode(Code39Encoder.getInstance(),
                    WidthCodedPainter.getInstance(),
                    EAN13TextPainter.getInstance());

            // 尺寸，面积，大小 密集程度
            productBarcode.setXDimension(Double.valueOf(dimension).doubleValue());
            // 高度 10.0 = 1cm 默认1.5cm
            productBarcode.setBarHeight(Double.valueOf(barHeight).doubleValue());
            // 宽度
            productBarcode.setWideRatio(Double.valueOf(barWith).doubleValue());
            //是否显示字体
            productBarcode.setShowText(true);
            //显示字体样式
            productBarcode.setTextPainter(BaseLineTextPainter.getInstance());
            // 生成二维码
            BufferedImage bi  = productBarcode.createBarcode(strBarCode);

            ImageIO.write(bi, "png", outputStream);
            request.setCharacterEncoding("utf-8");

            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(outputStream.toByteArray());//返回Base64编码过的字节数组字符串
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidAtributeException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}